<template>
  <div class="space-y-6">
    <!-- 页面标题和操作按钮 -->
    <!-- <div class="flex justify-between items-center">
      <div>
        <h2 class="text-2xl font-bold text-gray-900">问卷管理</h2>
        <p class="text-gray-600 mt-1">管理所有问卷的创建、编辑和发布</p>
      </div>
      <Button 
        label="创建问卷" 
        icon="pi pi-plus" 
        @click="showCreateDialog = true"
        class="bg-blue-600 hover:bg-blue-700"
      />
    </div> -->

    <!-- 搜索和筛选 -->
    <div class="bg-white p-6 rounded-lg shadow-sm">
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">问卷标题</label>
          <InputText 
            v-model="searchForm.title" 
            placeholder="搜索问卷标题"
            class="w-full"
          />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">状态</label>
          <Dropdown 
            v-model="searchForm.status" 
            :options="statusOptions" 
            optionLabel="label" 
            optionValue="value"
            placeholder="选择状态"
            class="w-full"
          />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">创建时间</label>
          <Calendar 
            v-model="searchForm.createTime" 
            placeholder="选择日期"
            class="w-full"
          />
        </div>
        <div class="flex items-end">
          <Button 
            label="搜索" 
            icon="pi pi-search" 
            @click="searchQuestionnaires"
            class="mr-2"
          />
          <Button 
            label="重置" 
            icon="pi pi-refresh" 
            severity="secondary" 
            @click="resetSearch"
          />
        </div>
      </div>
    </div>

    <!-- 问卷列表 -->
    <div class="bg-white rounded-lg shadow-sm p-6 h-[calc(100vh-254px)]">
      <DataTable 
        :value="questionnaires" 
        :loading="loading"
        :paginator="true" 
        :rows="10"
        :totalRecords="totalRecords"
        :lazy="true"
        @page="onPageChange"
        class="p-0"
        stripedRows
      >
        <Column field="id" header="ID" sortable style="width: 80px">
          <template #body="{ index }">
            {{ index + 1 }}
          </template>
        </Column>
        <Column field="title" header="问卷标题" sortable>
          <template #body="{ data }">
            <div class="font-medium text-gray-900">{{ data.title }}</div>
            <div class="text-sm text-gray-500">{{ data.description }}</div>
          </template>
        </Column>
        <Column field="status" header="状态" sortable style="width: 120px">
          <template #body="{ data }">
            <Tag 
              :value="getStatusLabel(data.status)" 
              :severity="getStatusSeverity(data.status)"
            />
          </template>
        </Column>
        <Column field="createTime" header="创建时间" sortable style="width: 180px">
          <template #body="{ data }">
            {{ formatDate(data.createTime) }}
          </template>
        </Column>
        <Column header="操作" style="width: 200px">
          <template #body="{ data }">
            <div class="flex space-x-2">
              <Button 
                icon="pi pi-eye" 
                severity="info" 
                text 
                @click="viewQuestionnaire(data)"
                v-tooltip.top="'查看详情'"
              />
              <Button 
                icon="pi pi-pencil" 
                severity="warning" 
                text 
                @click="editQuestionnaire(data)"
                v-tooltip.top="'编辑问卷'"
              />
              <Button 
                v-if="data.status === 0"
                icon="pi pi-check" 
                severity="success" 
                text 
                @click="publishQuestionnaire(data.id)"
                v-tooltip.top="'发布问卷'"
              />
              <Button 
                v-if="data.status === 1"
                icon="pi pi-times" 
                severity="secondary" 
                text 
                @click="offlineQuestionnaire(data.id)"
                v-tooltip.top="'下线问卷'"
              />
              <Button 
                icon="pi pi-trash" 
                severity="danger" 
                text 
                @click="deleteQuestionnaire(data.id)"
                v-tooltip.top="'删除问卷'"
              />
            </div>
          </template>
        </Column>
      </DataTable>
    </div>

    <!-- 创建/编辑问卷对话框 -->
    <Dialog 
      v-model:visible="showCreateDialog" 
      :header="isEditing ? '编辑问卷' : '创建问卷'"
      modal 
      class="w-full max-w-2xl"
    >
      <div class="space-y-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">问卷标题 *</label>
          <InputText 
            v-model="questionnaireForm.title" 
            placeholder="请输入问卷标题"
            class="w-full"
          />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">问卷描述</label>
          <Textarea 
            v-model="questionnaireForm.description" 
            placeholder="请输入问卷描述"
            rows="3"
            class="w-full"
          />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">状态</label>
          <Dropdown 
            v-model="questionnaireForm.status" 
            :options="statusOptions" 
            optionLabel="label" 
            optionValue="value"
            placeholder="选择状态"
            class="w-full"
          />
        </div>
      </div>
      
      <template #footer>
        <div class="flex justify-end space-x-2">
          <Button 
            label="取消" 
            severity="secondary" 
            @click="showCreateDialog = false"
          />
          <Button 
            :label="isEditing ? '更新' : '创建'" 
            @click="saveQuestionnaire"
            :loading="saving"
          />
        </div>
      </template>
    </Dialog>

    <!-- 问卷详情对话框 -->
    <Dialog 
      v-model:visible="showDetailDialog" 
      header="问卷详情"
      modal 
      class="w-full max-w-4xl"
    >
      <div v-if="selectedQuestionnaire" class="space-y-4">
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700">问卷标题</label>
            <p class="mt-1 text-gray-900">{{ selectedQuestionnaire.title }}</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700">状态</label>
            <Tag 
              :value="getStatusLabel(selectedQuestionnaire.status)" 
              :severity="getStatusSeverity(selectedQuestionnaire.status)"
              class="mt-1"
            />
          </div>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700">问卷描述</label>
          <p class="mt-1 text-gray-900">{{ selectedQuestionnaire.description }}</p>
        </div>
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700">创建时间</label>
            <p class="mt-1 text-gray-900">{{ formatDate(selectedQuestionnaire.createTime) }}</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700">更新时间</label>
            <p class="mt-1 text-gray-900">{{ formatDate(selectedQuestionnaire.updateTime) }}</p>
          </div>
        </div>
      </div>
    </Dialog>

    <!-- 确认删除对话框 -->
    <ConfirmDialog />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { questionnaireApi } from '@/api/questionnaire.js'
import { useConfirm } from 'primevue/useconfirm'
import { useToast } from 'primevue/usetoast'

// PrimeVue 组件
import Button from 'primevue/button'
import InputText from 'primevue/inputtext'
import Dropdown from 'primevue/dropdown'
import Calendar from 'primevue/calendar'
import DataTable from 'primevue/datatable'
import Column from 'primevue/column'
import Tag from 'primevue/tag'
import Dialog from 'primevue/dialog'
import Textarea from 'primevue/textarea'
import ConfirmDialog from 'primevue/confirmdialog'
import { useRoute } from 'vue-router'

const confirm = useConfirm()
const toast = useToast()
const route = useRoute()

const currentSystem = computed(() => {
  return route.path.startsWith('/backstage/five') ? 'five' : 'pmpu'
})

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const questionnaires = ref([])
const totalRecords = ref(0)
const showCreateDialog = ref(false)
const showDetailDialog = ref(false)
const isEditing = ref(false)
const selectedQuestionnaire = ref(null)

// 搜索表单
const searchForm = reactive({
  title: '',
  status: null,
  createTime: null,
  page: 1,
  limit: 10
})

// 问卷表单
const questionnaireForm = reactive({
  id: null,
  title: '',
  description: '',
  status: 0
})

// 状态选项
const statusOptions = ref([
  { label: '草稿', value: 0 },
  { label: '已发布', value: 1 },
  { label: '已下线', value: 2 }
])

// 获取问卷列表
const getQuestionnaires = async () => {
  loading.value = true
  try {
    const response = await questionnaireApi.getQuestionnairePage(searchForm)
    if (response.success) {
      if (currentSystem.value === 'pmpu') {
        questionnaires.value = response.data.records.slice(0, 1)
      } else {
        questionnaires.value = response.data.records.slice(1)
      }
      totalRecords.value = response.data.total || 0
    }
  } catch (error) {
    toast.add({
      severity: 'error',
      summary: '错误',
      detail: '获取问卷列表失败',
      life: 3000
    })
  } finally {
    loading.value = false
  }
}

// 搜索问卷
const searchQuestionnaires = () => {
  searchForm.page = 1
  getQuestionnaires()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    title: '',
    status: null,
    createTime: null,
    page: 1,
    limit: 10
  })
  getQuestionnaires()
}

// 分页变化
const onPageChange = (event) => {
  searchForm.page = event.page + 1
  searchForm.limit = event.rows
  getQuestionnaires()
}

// 查看问卷详情
const viewQuestionnaire = (questionnaire) => {
  selectedQuestionnaire.value = questionnaire
  showDetailDialog.value = true
}

// 编辑问卷
const editQuestionnaire = (questionnaire) => {
  isEditing.value = true
  Object.assign(questionnaireForm, {
    id: questionnaire.id,
    title: questionnaire.title,
    description: questionnaire.description,
    status: questionnaire.status
  })
  showCreateDialog.value = true
}

// 保存问卷
const saveQuestionnaire = async () => {
  if (!questionnaireForm.title.trim()) {
    toast.add({
      severity: 'warn',
      summary: '警告',
      detail: '请输入问卷标题',
      life: 3000
    })
    return
  }

  saving.value = true
  try {
    const api = isEditing.value ? questionnaireApi.updateQuestionnaire : questionnaireApi.createQuestionnaire
    const response = await api(questionnaireForm)
    
    if (response.success) {
      toast.add({
        severity: 'success',
        summary: '成功',
        detail: isEditing.value ? '问卷更新成功' : '问卷创建成功',
        life: 3000
      })
      showCreateDialog.value = false
      resetForm()
      getQuestionnaires()
    }
  } catch (error) {
    toast.add({
      severity: 'error',
      summary: '错误',
      detail: isEditing.value ? '问卷更新失败' : '问卷创建失败',
      life: 3000
    })
  } finally {
    saving.value = false
  }
}

// 发布问卷
const publishQuestionnaire = async (id) => {
  try {
    const response = await questionnaireApi.publishQuestionnaire(id)
    if (response.success) {
      toast.add({
        severity: 'success',
        summary: '成功',
        detail: '问卷发布成功',
        life: 3000
      })
      getQuestionnaires()
    }
  } catch (error) {
    toast.add({
      severity: 'error',
      summary: '错误',
      detail: '问卷发布失败',
      life: 3000
    })
  }
}

// 下线问卷
const offlineQuestionnaire = async (id) => {
  try {
    const response = await questionnaireApi.offlineQuestionnaire(id)
    if (response.success) {
      toast.add({
        severity: 'success',
        summary: '成功',
        detail: '问卷下线成功',
        life: 3000
      })
      getQuestionnaires()
    }
  } catch (error) {
    toast.add({
      severity: 'error',
      summary: '错误',
      detail: '问卷下线失败',
      life: 3000
    })
  }
}

// 删除问卷
const deleteQuestionnaire = (id) => {
  confirm.require({
    message: '确定要删除这个问卷吗？此操作不可恢复。',
    header: '确认删除',
    icon: 'pi pi-exclamation-triangle',
    accept: async () => {
      try {
        const response = await questionnaireApi.deleteQuestionnaire(id)
        if (response.success) {
          toast.add({
            severity: 'success',
            summary: '成功',
            detail: '问卷删除成功',
            life: 3000
          })
          getQuestionnaires()
        }
      } catch (error) {
        toast.add({
          severity: 'error',
          summary: '错误',
          detail: '问卷删除失败',
          life: 3000
        })
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  Object.assign(questionnaireForm, {
    id: null,
    title: '',
    description: '',
    status: 0
  })
  isEditing.value = false
}

// 获取状态标签
const getStatusLabel = (status) => {
  const option = statusOptions.value.find(opt => opt.value === status)
  return option ? option.label : '未知'
}

// 获取状态严重程度
const getStatusSeverity = (status) => {
  switch (status) {
    case 0: return 'warning'
    case 1: return 'success'
    case 2: return 'secondary'
    default: return 'info'
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 监听对话框关闭
const handleDialogClose = () => {
  resetForm()
}

// 组件挂载时获取数据
onMounted(() => {
  getQuestionnaires()
})
</script>

<style scoped>
/* 自定义样式 */
</style>
